/**
 * Created by mola on 15-12-10.
 */

'use strict';
var passwordConfig = require('./passwordConfig');
var crypto = require('crypto');


class PasswordGenerator {
    /**
     * @param config {passwordConfig.PasswordConfig}
     */
    constructor(config) {
        if (!config) {
            config = new passwordConfig.PasswordConfig();
        }
        this.config = config;
    }

    /**
     * @param secret {string}
     * @param key {string}
     * @param callback {function}
     * @returns {string}
     */
    generatePass(secret, key, callback) {
        let sha256 = crypto.createHash('sha256');
        sha256.update(secret);
        let first = sha256.digest();
        sha256 = crypto.createHash('sha256');
        sha256.update(key);
        let second = sha256.digest();

        let offset = 0;
        let position = 0;
        let result = String();
        let passwordArray = this.config.getPasswordSetArray();

        for (let i = 0; i < this.config.length; i++) {
            if (position >= first.length) {
                position = position % first.length;
                offset++;
            }
            let secondPos = (offset + position) % second.length;
            let number = first[position] ^ second[secondPos];
            result = result.concat(passwordArray[number % passwordArray.length]);
            position++;
        }
        if (callback) {
            callback(null, result);
        }
        return result;
    }
}

/**
 * @param config {passwordConfig.PasswordConfig}
 */
module.exports = function (config) {
    return new PasswordGenerator(config);
};
